package com.neuedu.his.controller;

import com.neuedu.his.po.*;
import com.neuedu.his.service.CheckapplyService;
import com.neuedu.his.service.DepartmentService;
import com.neuedu.his.service.RegisterService;
import com.neuedu.his.service.SettlecategoryService;
import com.neuedu.his.service.UserService;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/examine")
public class examineController {

    @Resource
    private RegisterService registerService;
    @Resource
    private UserService userService;
    @Resource
    private SettlecategoryService settlecategoryService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private CheckapplyService checkapplyService;

    /**
     * 获取患者列表（左侧表格）
     */
    @GetMapping("/patients")
    public List<Register> getPatientList() {
        return registerService.list();
    }

    /**
     * 获取患者详情（右上侧表单）
     */
    @GetMapping("/patients/{id}")
    public PatientDetailVO getPatientDetail(@PathVariable Integer id) {
        Register reg = registerService.getById(id);
        if (reg == null) return null;

        // 关联查询开单医生（user表）
        User doctor = userService.getById(reg.getUserid());
        String doctorName = doctor != null ? doctor.getRealName() : "";

        // 关联查询结算类别（settlecategory表）
        Settlecategory settle = settlecategoryService.getById(reg.getSettleid());
        String settleCode = settle != null ? settle.getSettlecode() : "";

        // 关联查询就诊科室（department表）
        Department dept = departmentService.getById(reg.getDeptid());
        String deptName = dept != null ? dept.getDeptname() : "";

        // 封装患者详情VO
        PatientDetailVO vo = new PatientDetailVO();
        vo.setCaseNumber(reg.getCasenumber());
        vo.setRealName(reg.getRealname());
        vo.setAge(reg.getAge() + reg.getAgetype());
        vo.setSettleCategory(settleCode);
        vo.setDepartment(deptName);
        vo.setPrescriptionStatus(""); // 暂空
        vo.setChargeDate(""); // 暂空
        vo.setDoctorName(doctorName);
        vo.setInvoiceNo(""); // 暂空
        return vo;
    }

    /**
     * 获取检验项目（右下侧表格）
     */
    @GetMapping("/checks/{registId}")
    public List<CheckapplyVO> getCheckItems(@PathVariable Integer registId) {
        // 使用MyBatis-Plus条件查询
        List<Checkapply> applies = checkapplyService.lambdaQuery()
                .eq(Checkapply::getRegistid, registId)
                .list();

        // 转换为VO
        List<CheckapplyVO> voList = new ArrayList<>();
        for (Checkapply apply : applies) {
            CheckapplyVO vo = new CheckapplyVO();
            vo.setId(apply.getId());
            vo.setName(apply.getName());
            vo.setPosition(apply.getPosition());
            vo.setNum(apply.getNum());
            vo.setUnit("次");
            vo.setPrice(""); // 暂空
            vo.setTotalAmount(""); // 暂空
            vo.setState(apply.getState() == 1 ? "未检" : "已检");
            voList.add(vo);
        }
        return voList;
    }

    /**
     * 执行确认（状态改为已检）
     */
    @PostMapping("/execute")
    public boolean executeConfirm(@RequestBody List<Integer> checkIds) {
        checkIds.forEach(id -> {
            Checkapply apply = checkapplyService.getById(id);
            if (apply != null) {
                apply.setState(2);
                checkapplyService.updateById(apply);
            }
        });
        return true;
    }

    /**
     * 取消执行（数量改为0）
     */
    @PostMapping("/cancel")
    public boolean cancelExecute(@RequestBody List<Integer> checkIds) {
        checkIds.forEach(id -> {
            Checkapply apply = checkapplyService.getById(id);
            if (apply != null) {
                apply.setNum(0);
                checkapplyService.updateById(apply);
            }
        });
        return true;
    }

    /**
     * 填写结果（更新数据库）
     */
    @PostMapping("/saveResults")
    public boolean saveResults(@RequestBody List<Checkapply> results) {
        return checkapplyService.updateBatchById(results);
    }

    // 患者详情VO
    public static class PatientDetailVO {
        private String caseNumber;
        private String realName;
        private String age;
        private String settleCategory;
        private String department;
        private String prescriptionStatus;
        private String chargeDate;
        private String doctorName;
        private String invoiceNo;

        // Getter和Setter
        public String getCaseNumber() { return caseNumber; }
        public void setCaseNumber(String caseNumber) { this.caseNumber = caseNumber; }
        public String getRealName() { return realName; }
        public void setRealName(String realName) { this.realName = realName; }
        public String getAge() { return age; }
        public void setAge(String age) { this.age = age; }
        public String getSettleCategory() { return settleCategory; }
        public void setSettleCategory(String settleCategory) { this.settleCategory = settleCategory; }
        public String getDepartment() { return department; }
        public void setDepartment(String department) { this.department = department; }
        public String getPrescriptionStatus() { return prescriptionStatus; }
        public void setPrescriptionStatus(String prescriptionStatus) { this.prescriptionStatus = prescriptionStatus; }
        public String getChargeDate() { return chargeDate; }
        public void setChargeDate(String chargeDate) { this.chargeDate = chargeDate; }
        public String getDoctorName() { return doctorName; }
        public void setDoctorName(String doctorName) { this.doctorName = doctorName; }
        public String getInvoiceNo() { return invoiceNo; }
        public void setInvoiceNo(String invoiceNo) { this.invoiceNo = invoiceNo; }
    }

    // 检验项目VO
    public static class CheckapplyVO {
        private Integer id;
        private String name;
        private String position;
        private Integer num;
        private String unit;
        private String price;
        private String totalAmount;
        private String state;

        // Getter和Setter
        public Integer getId() { return id; }
        public void setId(Integer id) { this.id = id; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getPosition() { return position; }
        public void setPosition(String position) { this.position = position; }
        public Integer getNum() { return num; }
        public void setNum(Integer num) { this.num = num; }
        public String getUnit() { return unit; }
        public void setUnit(String unit) { this.unit = unit; }
        public String getPrice() { return price; }
        public void setPrice(String price) { this.price = price; }
        public String getTotalAmount() { return totalAmount; }
        public void setTotalAmount(String totalAmount) { this.totalAmount = totalAmount; }
        public String getState() { return state; }
        public void setState(String state) { this.state = state; }
    }
}